/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.deployment.command;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.DeployedArtifact;
import org.eclipse.uml2.uml.Deployment;
import org.eclipse.uml2.uml.DeploymentTarget;

import com.cea.papyrus.core.PapyrusPlugin;
import com.cea.papyrus.core.helper.IGraphEdgeHelper;
import com.cea.papyrus.core.helper.IModelerHelper;

/**
 * 
 */
public class DeconnectDeployedArtifactFromModelCommand extends Command {

	/**
	 * debug channel.
	 */
	private int channel = 201;
	
	/**
	 * 
	 */
	private DeploymentTarget deploymentTarget;
	
	/**
	 * 
	 */
	private DeployedArtifact deployedArtifact;
	
	/**
	 * 
	 */
	private Deployment deployment;
	
	/**
	 * 
	 */
	private Object elementFactory;

	/**
	 * Default Constructor.
	 * 
	 * @param child the child
	 * @param deployment 
	 * @param deployedArtifact 
	 */
	public DeconnectDeployedArtifactFromModelCommand(DeployedArtifact deployedArtifact, Deployment deployment) {
		if (deployedArtifact == null) {
			throw new IllegalArgumentException();
		}
		IModelerHelper imodelerFactory= PapyrusPlugin.getDefault().getFactoryRegistry().getFactory(Deployment.class);
		elementFactory = imodelerFactory.getElementFactory(Deployment.class);
		setLabel("Delete <DeconnectDeployedArtifactFromModelCommand>");
		this.deployment = deployment;
		this.deployedArtifact = deployedArtifact;
		this.deploymentTarget = deployment.getLocation();
	}

	/**
	 * Execute.
	 */
	@Override
	public void execute() {
		// Deconnect deployed artifact from deployment target			
		((IGraphEdgeHelper)elementFactory).deconnect(deploymentTarget, deployedArtifact, deployment);			
		if (deployment.getSuppliers().isEmpty()){
			deploymentTarget.getClientDependencies().remove(deployment);
		}		
	}

	/**
	 * Redo.
	 */
	@Override
	public void redo() {
		execute();
	}

	/**
	 * Undo.
	 */
	@Override
	public void undo() {	
		//	Connect deployed artifact to deployment target	
		((IGraphEdgeHelper)elementFactory).connect(deploymentTarget, deployedArtifact, deployment);
		if (deployment.getSuppliers().isEmpty()){
			deploymentTarget.getDeployments().add(deployment);
		}	
	}

}
